package com.dayuanit.dy8.mall.springbootmall.service.impl;

import com.dayuanit.dy8.mall.springbootmall.dto.CartDTO;
import com.dayuanit.dy8.mall.springbootmall.entity.Cart;
import com.dayuanit.dy8.mall.springbootmall.entity.Commodity;
import com.dayuanit.dy8.mall.springbootmall.enums.CartStatusEnum;
import com.dayuanit.dy8.mall.springbootmall.mapper.CartMapper;
import com.dayuanit.dy8.mall.springbootmall.mapper.CommodityMapper;
import com.dayuanit.dy8.mall.springbootmall.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CommodityMapper commodityMapper;

    @Value("${image.url}")
    private String imgUrl;

    @Override
    public void add(int commonId, int buyNum, int userId) {
        //先查询购物车是否有相同的商品 有则更新数量 无则新增
        Cart cart = cartMapper.getCart(userId, commonId);
        if (null == cart) {
            cart = new Cart();
            cart.setBuyNum(buyNum);
            cart.setCommoId(commonId);
            cart.setCreateTime(new Date());
            cart.setModifyTime(new Date());
            cart.setStatus(CartStatusEnum.en_able.getK());
    //        cart.setStatus(1);//魔数 反面教材
            cart.setUserId(userId);
            cartMapper.insert(cart);
        } else {
            cart.setBuyNum(cart.getBuyNum() + buyNum);
            cartMapper.updateByPrimaryKey(cart);
        }
    }

    @Override
    public List<CartDTO> listCart(int userId) {

        final List<Cart> carts = cartMapper.listCart(userId);
        List<CartDTO> dtoList = new ArrayList<>(carts.size());

        for (Cart cart : carts) {
            final CartDTO cartDTO = new CartDTO();
            dtoList.add(cartDTO);
            final Commodity commodity = commodityMapper.getCommodity(cart.getCommoId());

            cartDTO.setBuyNum(cart.getBuyNum());
            cartDTO.setCartId(cart.getId());
            cartDTO.setCommoId(cart.getCommoId());
            cartDTO.setCommoName(commodity.getCommoName());
            cartDTO.setPicUrl(imgUrl + commodity.getPictureUrl());
            cartDTO.setPrice(commodity.getPrice());
        }

        return dtoList;
    }
}
